package com.joker.demo.controller;


import dev.langchain4j.model.chat.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 多模型共存
 *
 * @author : feixiang.li
 * @since : 2025-09-25 15:20
 */
@RestController
public class MultipleController {


    @Autowired
    @Qualifier("qwen")
    private ChatModel qwen;

    @Autowired
    @Qualifier("grok")
    private ChatModel grok;

    // 创建线程池来处理并发请求
    private final Executor executor = Executors.newFixedThreadPool(2);

    @RequestMapping("/multiple")
    public String multiple(@RequestParam(value = "question", defaultValue = "你是谁") String question) {

        // 开2个线程一起调用，一起返回结果
        CompletableFuture<String> qwenFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return "通义千问：\n" + qwen.chat(question);
            } catch (Exception e) {
                return "通义千问调用失败：" + e.getMessage();
            }
        }, executor);

        CompletableFuture<String> grokFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return "Grok：\n" + grok.chat(question);
            } catch (Exception e) {
                return "Grok调用失败：" + e.getMessage();
            }
        }, executor);

        // 等待两个任务都完成，然后组合结果
        CompletableFuture<String> combinedFuture = qwenFuture.thenCombine(grokFuture, (qwenResult, grokResult) -> {
            StringBuilder result = new StringBuilder();
            result.append("问题：").append(question).append("\n\n");
            result.append(qwenResult).append("\n\n");
            result.append("----------------------------------------\n\n");
            result.append(grokResult);
            return result.toString();
        });

        // 阻塞等待结果并返回
        try {
            return combinedFuture.get();
        } catch (Exception e) {
            return "请求处理失败：" + e.getMessage();
        }
    }
}
